compiler = require('../../src/compiler/compiler');

fs = require('fs');
path = require('path');
util  = require('util');
spawn = require('child_process').spawn;


var getExtension = function(filename) {
    var ext = path.extname(filename||'').split('.');
    return ext[ext.length - 1];
}

var walk = function(dir, done) {
  var results = [];
  fs.readdir(dir, function(err, list) {
    if (err) return done(err);
    var pending = list.length;
    if (!pending) return done(null, results);
    list.forEach(function(file) {
      file = dir + '/' + file;
      fs.stat(file, function(err, stat) {
        if (stat && stat.isDirectory()) {
          walk(file, function(err, res) {
            results = results.concat(res);
            if (!--pending) done(null, results);
          });
        } else {
          results.push(file);
          if (!--pending) done(null, results);
        }
      });
    });
  });
};

var spawnProcess = function(file, callback) {
	var batchjs, output, fileDir, fileName;
	
	fileDir = (file.substr(0, file.lastIndexOf('/')));
	fileName = file.substr(file.lastIndexOf('/')+1);

	batchjs = spawn('batchjs', [fileName], {cwd:fileDir});

	output = "";
	batchjs.stdout.on('data', function (data) {
	  	output = output + data;
	});

	batchjs.stderr.on('data', function (data) {
	  	output = output + data;
	});

	batchjs.on('exit', function (code) {
		// Write output to txt file
	    fs.stat(fileDir + "/output", function(err, stats) {
	        if( err || stats.isDirectory() ) {
	            fs.mkdir(fileDir + "/output", function() {
	                fs.writeFile(fileDir + "/output"+"/"+fileName+".txt", output, 'utf-8');
	            });
	        } else {
	            fs.writeFile(fileDir + "/output"+"/"+fileName+".txt", output, 'utf-8');
	        }
	    });
	    callback();
	});
}


rootDir = './'
if (process.argv[2] ) {
	rootDir = rootDir + process.argv[2];
}

walk(rootDir, function(err, res) {
	var bjsFiles = [];
	res.forEach(function(file) {
		if (getExtension(file) === 'bjs') {
			bjsFiles.push(file);
		}
	});

	var doSpawn = function(i) {
		if( typeof(bjsFiles[i]) != 'undefined' ) {
			console.log('Running: '+ bjsFiles[i]);
			spawnProcess(bjsFiles[i], function() {
				console.log('Done: '+ bjsFiles[i])
				doSpawn(i+1);
			});
		}
	}
	doSpawn(0);
});